<template>
  <div class="task-data-tab">
    <!-- 搜索卡片 -->
    <div class="search-section">
      <el-card shadow="hover" class="search-card">
        <template #header>
          <div class="search-header">
            <div class="search-title">
              <el-icon><Search /></el-icon>
              <span>搜索与筛选</span>
            </div>
          </div>
        </template>

        <el-form :model="searchForm" class="search-form">
          <div class="search-form-content">
            <div class="search-form-fields">
              <el-form-item label="环境">
                <el-select
                  v-model="searchForm.env_id"
                  placeholder="选择环境"
                  clearable
                  style="width: 200px"
                  @change="handleEnvChange"
                >
                  <el-option label="全部" value="" />
                  <el-option
                    v-for="env in store.envConfigsList"
                    :key="env.id"
                    :label="env.env_name"
                    :value="env.id"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="配置">
                <el-select
                  v-model="searchForm.config_id"
                  placeholder="选择配置"
                  clearable
                  filterable
                  style="width: 200px"
                >
                  <el-option label="全部" value="" />
                  <el-option
                    v-for="config in taskConfigsList"
                    :key="config.id"
                    :label="config.key_prefix"
                    :value="config.id"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="任务类型">
                <el-input
                  v-model="searchForm.task_type"
                  placeholder="任务类型"
                  clearable
                  style="width: 150px"
                />
              </el-form-item>

              <el-form-item label="删除状态">
                <el-select
                  v-model="searchForm.deletion_status"
                  placeholder="选择状态"
                  clearable
                  style="width: 140px"
                >
                  <el-option label="全部" value="" />
                  <el-option label="活跃" value="active" />
                  <el-option label="正常过期" value="normal_expire" />
                  <el-option label="提前删除" value="early_deleted" />
                </el-select>
              </el-form-item>

              <el-form-item label="搜索">
                <el-input
                  v-model="searchForm.search"
                  placeholder="Redis key、任务ID、用户ID"
                  clearable
                  style="width: 250px"
                  @keyup.enter="handleSearch"
                />
              </el-form-item>
            </div>

            <div class="search-form-actions">
              <el-button type="info" plain @click="toggleStats">
                <el-icon>
                  <component :is="showStats ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
                {{ showStats ? '隐藏统计' : '显示统计' }}
              </el-button>
              <el-button type="danger" @click="$router.push('/redis-task-monitor/task-config')" plain>
                <el-icon><Setting /></el-icon>
                任务监控配置
              </el-button>
              <el-button type="primary" @click="handleSearch" class="search-btn">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button type="warning" @click="handleReset" class="reset-btn">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </div>
          </div>
        </el-form>
      </el-card>
    </div>

    <!-- 统计数据卡片 -->
    <div v-if="store.taskDataStats && Object.keys(store.taskDataStats).length > 0" v-show="showStats" class="stats-section">
      <el-card shadow="hover" class="stats-card">
        <div class="stats-grid">
          <div class="stat-item">
            <div class="stat-label">总数据数</div>
            <div class="stat-value">{{ store.taskDataStats.total_count || 0 }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">活跃</div>
            <div class="stat-value success">{{ store.taskDataStats.active_count || 0 }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">正常过期</div>
            <div class="stat-value info">{{ store.taskDataStats.normal_expire_count || 0 }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">提前删除</div>
            <div class="stat-value warning">{{ store.taskDataStats.early_deleted_count || 0 }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">平均TTL</div>
            <div class="stat-value">{{ formatTTL(store.taskDataStats.avg_ttl) }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">总数据大小</div>
            <div class="stat-value">{{ formatBytes(store.taskDataStats.total_data_size) }}</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 表格卡片 -->
    <div class="table-section">
      <el-card shadow="hover" class="table-card">
        <template #header>
          <div class="table-header">
            <div class="table-title">
              <el-icon><List /></el-icon>
              <span>任务数据列表</span>
            </div>
            <div class="table-header-actions">
              <el-button type="success" @click="handleRefresh" class="refresh-btn" :loading="store.taskDataLoading" size="small">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
              <el-button type="info" @click="handleLoadStats" size="small">
                <el-icon><DataAnalysis /></el-icon>
                加载统计
              </el-button>
              <div class="table-info">
                <div class="pagination-control-wrapper clickable" @click="togglePagination">
                  <span class="page-count">本页 {{ store.taskData.length }} 条</span>
                  <div class="divider"></div>
                  <span class="pagination-info">
                    {{ store.taskDataPage }}/{{ Math.ceil(store.taskDataTotal / store.taskDataPageSize) || 1 }}
                  </span>
                  <el-icon class="pagination-toggle-icon">
                    <ArrowUp v-if="paginationVisible" />
                    <ArrowDown v-else />
                  </el-icon>
                </div>
              </div>
            </div>
          </div>
        </template>

        <div class="table-container">
          <el-table
            :data="store.taskData"
            class="enhanced-table"
            style="width: 100%"
            :height="600"
            table-layout="fixed"
            :stripe="false"
            :border="false"
            @sort-change="handleSortChange"
          >
            <el-table-column prop="id" label="ID" width="80" sortable="custom" />
            <el-table-column prop="redis_key" label="Redis Key" min-width="250" show-overflow-tooltip />
            <el-table-column prop="key_prefix" label="Key前缀" min-width="150" show-overflow-tooltip />
            <el-table-column prop="task_id" label="任务ID" min-width="120" show-overflow-tooltip>
              <template #default="{ row }">
                <span v-if="row.task_id">{{ row.task_id }}</span>
                <span v-else class="text-muted">-</span>
              </template>
            </el-table-column>
            <el-table-column prop="task_type" label="任务类型" width="100" align="center">
              <template #default="{ row }">
                <span v-if="row.task_type">{{ row.task_type }}</span>
                <span v-else class="text-muted">-</span>
              </template>
            </el-table-column>
            <el-table-column prop="user_id" label="用户ID" min-width="120" show-overflow-tooltip>
              <template #default="{ row }">
                <span v-if="row.user_id">{{ row.user_id }}</span>
                <span v-else class="text-muted">-</span>
              </template>
            </el-table-column>
            <el-table-column prop="ttl" label="TTL" width="100" align="right" sortable="custom">
              <template #default="{ row }">
                <span v-if="row.ttl !== null && row.ttl !== undefined">{{ formatTTL(row.ttl) }}</span>
                <span v-else class="text-muted">-</span>
              </template>
            </el-table-column>
            <el-table-column prop="expire_time" label="过期时间" width="180" sortable="custom">
              <template #default="{ row }">
                <span v-if="row.expire_time">{{ row.expire_time }}</span>
                <span v-else class="text-muted">-</span>
              </template>
            </el-table-column>
            <el-table-column prop="data_size" label="数据大小" width="120" align="right" sortable="custom">
              <template #default="{ row }">
                <span v-if="row.data_size !== null && row.data_size !== undefined">
                  {{ formatBytes(row.data_size) }}
                </span>
                <span v-else class="text-muted">-</span>
              </template>
            </el-table-column>
            <el-table-column prop="data_type" label="数据类型" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="getDataTypeTag(row.data_type)" size="small">
                  {{ row.data_type || 'string' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="deletion_status" label="删除状态" width="120" align="center" sortable="custom">
              <template #default="{ row }">
                <el-tag :type="getDeletionStatusTag(row.deletion_status)" size="small">
                  {{ getDeletionStatusText(row.deletion_status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="collection_time" label="采集时间" width="180" sortable="custom" />
            <el-table-column label="操作" width="220" fixed="right">
              <template #default="{ row }">
                <div class="action-buttons">
                  <el-tooltip content="查看详情" placement="top">
                    <el-button
                      type="primary"
                      size="small"
                      @click="handleViewDetail(row)"
                      circle
                    >
                      <el-icon><View /></el-icon>
                    </el-button>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页 -->
        <transition name="pagination-slide">
          <div v-show="paginationVisible" class="pagination-section">
            <el-pagination
              v-model:current-page="store.taskDataPage"
              v-model:page-size="store.taskDataPageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="store.taskDataTotal"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
              background
            />
          </div>
        </transition>
      </el-card>
    </div>

    <!-- 任务数据详情对话框 -->
    <TaskDataDetailDialog
      v-model="detailDialogVisible"
      :task-data="currentTaskData"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import {
  Search, Refresh, List, View, DataAnalysis, Setting,
  ArrowUp, ArrowDown
} from '@element-plus/icons-vue'
import { useRedisTaskMonitorStore } from '@/stores/redisTaskMonitor'
import TaskDataDetailDialog from './dialogs/TaskDataDetailDialog.vue'
import { createLogger } from '@/utils/logger'

const componentLogger = createLogger('TaskDataTab')
const store = useRedisTaskMonitorStore()

const searchForm = reactive({
  env_id: '',
  config_id: '',
  task_type: '',
  deletion_status: '',
  search: ''
})

const paginationVisible = ref(false)
const showStats = ref(false)
const detailDialogVisible = ref(false)
const currentTaskData = ref(null)
const sortField = ref('collection_time')
const sortOrder = ref('desc')

// 任务配置列表（根据选择的环境过滤）
const taskConfigsList = computed(() => {
  if (searchForm.env_id) {
    return store.taskConfigs.filter(config => config.env_id === searchForm.env_id)
  }
  return store.taskConfigs
})

// 获取删除状态标签
const getDeletionStatusTag = (status) => {
  const statusMap = {
    active: 'success',
    normal_expire: 'info',
    early_deleted: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取删除状态文本
const getDeletionStatusText = (status) => {
  const statusMap = {
    active: '活跃',
    normal_expire: '正常过期',
    early_deleted: '提前删除'
  }
  return statusMap[status] || status
}

// 获取数据类型标签
const getDataTypeTag = (type) => {
  const typeMap = {
    string: 'primary',
    hash: 'success',
    list: 'warning',
    set: 'info',
    zset: 'danger'
  }
  return typeMap[type] || 'info'
}

// 格式化TTL
const formatTTL = (ttl) => {
  if (ttl === null || ttl === undefined) return '-'
  if (ttl === -1) return '永不过期'
  if (ttl === -2) return '不存在'
  if (ttl < 60) return `${ttl}秒`
  if (ttl < 3600) return `${Math.floor(ttl / 60)}分钟`
  if (ttl < 86400) return `${Math.floor(ttl / 3600)}小时`
  return `${Math.floor(ttl / 86400)}天`
}

// 格式化字节
const formatBytes = (bytes) => {
  if (bytes === null || bytes === undefined || bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
}

// 环境变化处理
const handleEnvChange = async () => {
  // 当环境变化时，加载该环境下的任务配置列表
  searchForm.config_id = ''
  if (searchForm.env_id) {
    await store.fetchTaskConfigs({ env_id: searchForm.env_id, page: 1, pageSize: 1000 })
  }
}

// 搜索
const handleSearch = async () => {
  store.taskDataPage = 1
  await fetchData()
  await fetchStats()
}

// 重置
const handleReset = () => {
  searchForm.env_id = ''
  searchForm.config_id = ''
  searchForm.task_type = ''
  searchForm.deletion_status = ''
  searchForm.search = ''
  store.taskDataPage = 1
  fetchData()
  fetchStats()
}

// 刷新
const handleRefresh = () => {
  fetchData()
}

// 加载统计
const handleLoadStats = async () => {
  await fetchStats()
}

// 查看详情
const handleViewDetail = async (row) => {
  try {
    const data = await store.fetchTaskDataDetail(row.id)
    currentTaskData.value = data
    detailDialogVisible.value = true
  } catch (error) {
    componentLogger.error('获取任务数据详情失败', error)
  }
}

// 排序
const handleSortChange = ({ prop, order }) => {
  if (prop) {
    sortField.value = prop
    sortOrder.value = order === 'ascending' ? 'asc' : 'desc'
    fetchData()
  }
}

// 分页
const handleSizeChange = (size) => {
  store.taskDataPageSize = size
  store.taskDataPage = 1
  fetchData()
}

const handlePageChange = (page) => {
  store.taskDataPage = page
  fetchData()
}

const togglePagination = () => {
  paginationVisible.value = !paginationVisible.value
}

const toggleStats = () => {
  showStats.value = !showStats.value
}

// 获取统计数据
const fetchStats = async () => {
  try {
    const params = {}
    
    if (searchForm.env_id) {
      params.env_id = searchForm.env_id
    }
    
    if (searchForm.config_id) {
      params.config_id = searchForm.config_id
    }
    
    if (searchForm.task_type) {
      params.task_type = searchForm.task_type
    }
    
    if (searchForm.deletion_status) {
      params.deletion_status = searchForm.deletion_status
    }

    await store.fetchTaskDataStats(params)
  } catch (error) {
    componentLogger.error('获取任务数据统计失败', error)
  }
}

// 获取数据
const fetchData = async () => {
  try {
    const params = {
      page: store.taskDataPage,
      pageSize: store.taskDataPageSize,
      sort: sortField.value,
      order: sortOrder.value
    }

    if (searchForm.env_id) {
      params.env_id = searchForm.env_id
    }

    if (searchForm.config_id) {
      params.config_id = searchForm.config_id
    }

    if (searchForm.task_type) {
      params.task_type = searchForm.task_type
    }

    if (searchForm.deletion_status) {
      params.deletion_status = searchForm.deletion_status
    }

    if (searchForm.search) {
      params.search = searchForm.search
    }

    await store.fetchTaskData(params)
  } catch (error) {
    componentLogger.error('获取任务数据列表失败', error)
  }
}

// 导出方法供父组件调用
defineExpose({
  fetchData
})

onMounted(async () => {
  // 加载环境列表
  await store.fetchEnvConfigsList()
  // 加载数据
  await fetchData()
  // 加载统计
  await fetchStats()
})
</script>

<style scoped>
.task-data-tab {
  padding: 0;
}

.search-section {
  margin-bottom: 24px;
}

.stats-section {
  margin-bottom: 20px;
}

.stats-card {
  border-radius: 8px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 20px;
}

.stat-item {
  text-align: center;
}

.stat-label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.stat-value.success {
  color: #67c23a;
}

.stat-value.info {
  color: #409eff;
}

.stat-value.warning {
  color: #f56c6c;
}

.search-card,
.table-card {
  border-radius: 8px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: #303133;
}

.search-form {
  margin-top: 0;
}

.search-form-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
  flex-wrap: wrap;
}

.search-form-fields {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
  flex: 1;
}

.search-form-actions {
  display: flex;
  gap: 10px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: #303133;
}

.table-header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-control-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.pagination-control-wrapper:hover {
  background-color: #f5f7fa;
}

.page-count {
  font-size: 12px;
  color: #606266;
}

.divider {
  width: 1px;
  height: 14px;
  background-color: #dcdfe6;
}

.pagination-info {
  font-size: 12px;
  color: #909399;
}

.pagination-toggle-icon {
  font-size: 12px;
  color: #909399;
}

.table-container {
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.text-muted {
  color: #909399;
  font-style: italic;
}

.pagination-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.pagination-slide-enter-active,
.pagination-slide-leave-active {
  transition: all 0.3s ease;
}

.pagination-slide-enter-from,
.pagination-slide-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}
</style>
